"""
LLM模型相关的路由
提供模型的增删改查API
"""

from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_

from dao.postgresql_connect import get_db
from models import LLMModel, ModelModality, ModelStatus
from routers.auth import get_current_user
from models.user import User, UserRole
from schemas.generated.llm import (
    LLMModelCreateRequest, LLMModelUpdateRequest, LLMModelResponse, 
    LLMModelListResponse, LLMModelFilterRequest, LLMModelPaginationRequest,
    MessageResponse
)

# 创建路由
llm_create_router = APIRouter(
    prefix="/llm-create",
    tags=["llm-create"],
    responses={404: {"description": "Not found"}},
)

# 管理员权限验证
async def get_admin_user(current_user: User = Depends(get_current_user)) -> User:
    """
    验证当前用户是否为管理员
    
    Args:
        current_user: 当前用户
        
    Returns:
        User: 当前用户对象
        
    Raises:
        HTTPException: 用户不是管理员时抛出
    """
    if current_user.role != UserRole.ADMIN:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以执行此操作"
        )
    return current_user

# API端点
@llm_create_router.post("/create", response_model=LLMModelResponse, status_code=status.HTTP_201_CREATED)
async def create_llm_model(
    model: LLMModelCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """
    创建新的LLM模型
    
    Args:
        model: 模型信息
        db: 数据库会话
        current_user: 当前用户（管理员）
        
    Returns:
        LLMModelResponse: 创建的模型信息
    """
    # 检查model_id是否已存在
    existing_model = db.query(LLMModel).filter(LLMModel.model_id == model.model_id).first()
    if existing_model:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"模型ID '{model.model_id}' 已存在"
        )
    
    # 创建新模型
    db_model = LLMModel(
        **model.dict(),
        created_by=current_user.id,
        updated_by=current_user.id
    )
    
    db.add(db_model)
    db.commit()
    db.refresh(db_model)
    
    return db_model

@llm_create_router.get("/list-models", response_model=LLMModelListResponse)
async def list_llm_models(
    pagination: LLMModelPaginationRequest = Depends(),
    filter: Optional[LLMModelFilterRequest] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """
    获取LLM模型列表
    
    Args:
        pagination: 分页参数
        filter: 筛选条件
        db: 数据库会话
        current_user: 当前用户（管理员）
        
    Returns:
        LLMModelListResponse: 模型列表及分页信息
    """
    query = db.query(LLMModel)
    
    # 应用筛选条件
    if filter:
        if filter.provider:
            query = query.filter(LLMModel.provider == filter.provider)
        if filter.modality:
            query = query.filter(LLMModel.modality == filter.modality)
        if filter.status:
            query = query.filter(LLMModel.status == filter.status)
        if filter.search:
            search_term = f"%{filter.search}%"
            query = query.filter(
                or_(
                    LLMModel.name.ilike(search_term),
                    LLMModel.description.ilike(search_term)
                )
            )
    
    # 应用排序
    if pagination.sort_order == "asc":
        query = query.order_by(getattr(LLMModel, pagination.sort_by.value).asc())
    else:
        query = query.order_by(getattr(LLMModel, pagination.sort_by.value).desc())
    
    # 计算总记录数
    total = query.count()
    
    # 分页
    models = query.offset(pagination.skip).limit(pagination.limit).all()
    
    # 计算总页数
    pages = (total + pagination.limit - 1) // pagination.limit if pagination.limit > 0 else 0
    
    # 将 SQLAlchemy 模型实例转换为字典，再创建 Pydantic 模型实例
    model_responses = []
    for model in models:
        model_dict = {
            "id": model.id,
            "name": model.name,
            "model_id": model.model_id,
            "provider": model.provider,
            "modality": model.modality.value,
            "base_url": model.base_url,
            "api_key": model.api_key,
            "status": model.status.value,
            "description": model.description,
            "config": model.config,
            "created_at": model.created_at,
            "updated_at": model.updated_at,
            "created_by": model.created_by,
            "updated_by": model.updated_by
        }
        model_responses.append(LLMModelResponse.model_validate(model_dict))
    
    return LLMModelListResponse(
        items=model_responses,
        total=total,
        page=pagination.skip // pagination.limit + 1 if pagination.limit > 0 else 1,
        size=pagination.limit,
        pages=pages
    )

@llm_create_router.get("/models/{model_id}", response_model=LLMModelResponse)
async def get_llm_model(
    model_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """
    获取指定ID的LLM模型
    
    Args:
        model_id: 模型ID
        db: 数据库会话
        current_user: 当前用户（管理员）
        
    Returns:
        LLMModelResponse: 模型信息
        
    Raises:
        HTTPException: 模型不存在时抛出
    """
    model = db.query(LLMModel).filter(LLMModel.id == model_id).first()
    
    if not model:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"ID为 {model_id} 的模型不存在"
        )
    
    return model

@llm_create_router.put("/models/{model_id}", response_model=LLMModelResponse)
async def update_llm_model(
    model_id: int,
    model_update: LLMModelUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """
    更新指定ID的LLM模型
    
    Args:
        model_id: 模型ID
        model_update: 更新的模型信息
        db: 数据库会话
        current_user: 当前用户（管理员）
        
    Returns:
        LLMModelResponse: 更新后的模型信息
        
    Raises:
        HTTPException: 模型不存在时抛出
    """
    db_model = db.query(LLMModel).filter(LLMModel.id == model_id).first()
    
    if not db_model:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"ID为 {model_id} 的模型不存在"
        )
    
    # 更新模型信息
    update_data = model_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_model, key, value)
    
    # 更新审计字段
    db_model.updated_by = current_user.id
    
    db.commit()
    db.refresh(db_model)
    
    return db_model

@llm_create_router.delete("/models/{model_id}", response_model=MessageResponse)
async def delete_llm_model(
    model_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """
    删除指定ID的LLM模型
    
    Args:
        model_id: 模型ID
        db: 数据库会话
        current_user: 当前用户（管理员）
        
    Returns:
        MessageResponse: 删除成功的消息
        
    Raises:
        HTTPException: 模型不存在时抛出
    """
    db_model = db.query(LLMModel).filter(LLMModel.id == model_id).first()
    
    if not db_model:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"ID为 {model_id} 的模型不存在"
        )
    
    db.delete(db_model)
    db.commit()
    
    return MessageResponse(message=f"模型 {model_id} 已成功删除")
